# TriggerSwitchD, executes commands to activate/deactive remote switches.
# (c) Copyright 2010 Pontus Strömdahl, AdhocSkill. 
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


module TriggerSwitchD
  module SwitchFactory
    #Creates the Switch class dynamically from values, which is
    #assumed to be an Array of attributes/keys
    def self.new(values)
      definition = <<-EOS
      class Switch
        attr_reader #{values.map {|name| ":#{name}"}.join(",")}
        def initialize(value)
          value.each_pair do |key,value|
            instance_variable_set("@"+key.to_s,value) if respond_to?(key)
          end
        end
        
        def to_a_by_keys(keys)
          keys.map do |key|
            send(key)
          end
        end
      end
      EOS
      ::TriggerSwitchD.module_eval(definition)
      ::TriggerSwitchD.const_get("Switch")
    end
  end
end